package org.example._01_game;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *  txt 文件转化为 xlsx
 */
public class _04_TxtToExcelConverter {

    public static void main(String[] args) {
        String inputFile = "/Users/eddy/Desktop/test.txt";
        String outputFile = "/Users/eddy/Desktop/output.xlsx";
        try {
            // 读取txt文件
            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            String line;
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
            int rowNum = 0;
            while ((line = reader.readLine()) != null) {
                // 将每一行以逗号分隔的字符串分割成数组
                String[] values = line.split(",");
                // 创建行和单元格，并将数组中的每个元素写入单元格中
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < values.length; i++) {
                    Cell cell = row.createCell(i);
                    cell.setCellValue(values[i]);
                }
            }
            // 将Excel文件写入磁盘
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            System.out.println("转换完成！");
        } catch (IOException e) {
            System.err.println("转换失败：" + e.getMessage());
        }
    }
}
